<template>
  <div class="question-manage">
    <div class="header">
      <h2>知识问答管理</h2>
      <div class="actions">
        <el-button type="primary" @click="handleAdd">添加问题</el-button>
      </div>
    </div>

    <!-- 搜索表单 -->
    <el-form :inline="true" :model="searchForm" class="search-form">
      <el-form-item label="分类" style="width: 200px;">  <!--分类长度 -->
        <el-select v-model="searchForm.categoryId" placeholder="选择分类" clearable>
          <el-option
            v-for="item in categories"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="难度" style="width: 200px;">
        <el-select v-model="searchForm.difficulty" placeholder="选择难度" clearable>
          <el-option label="简单" :value="1" />
          <el-option label="中等" :value="2" />
          <el-option label="困难" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 问题列表 -->
    <el-table 
      :data="questionList" 
      border 
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="content" label="问题内容" show-overflow-tooltip />
      <el-table-column prop="categoryId" label="分类" width="100">
        <template #default="{ row }">
          {{ getCategoryName(row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column prop="difficulty" label="难度" width="100">
        <template #default="{ row }">
          <el-tag :type="getDifficultyType(row.difficulty)">
            {{ getDifficultyLabel(row.difficulty) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="answer" label="答案" width="100" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑/添加对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑问题' : '添加问题'"
      width="60%"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="选择分类">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="问题内容" prop="content">
          <el-input v-model="form.content" type="textarea" rows="3" />
        </el-form-item>
        <el-form-item label="选项" prop="optionList">
          <div v-for="(option, index) in form.optionList" :key="index" class="option-item">
            <el-input v-model="form.optionList[index]" placeholder="请输入选项内容">
              <template #prepend>选项 {{ String.fromCharCode(65 + index) }}</template>
            </el-input>
            <el-button 
              v-if="index === form.optionList.length - 1" 
              type="primary" 
              circle
              @click="addOption"
            >
              <el-icon><Plus /></el-icon>
            </el-button>
            <el-button 
              v-if="form.optionList.length > 2" 
              type="danger" 
              circle
              @click="removeOption(index)"
            >
              <el-icon><Minus /></el-icon>
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="正确答案" prop="answer">
          <el-radio-group v-model="form.answer">
            <el-radio 
              v-for="(_, index) in form.optionList" 
              :key="index" 
              :label="String.fromCharCode(65 + index)"
            >
              选项 {{ String.fromCharCode(65 + index) }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难度" prop="difficulty">
          <el-rate v-model="form.difficulty" :max="3" />
        </el-form-item>
        <el-form-item label="解析" prop="explanation">
          <el-input v-model="form.explanation" type="textarea" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Minus } from '@element-plus/icons-vue'
import request from '@/utils/request'

// 分类数据
const categories = [
  { id: 1, name: '中药基础' },
  { id: 2, name: '针灸推拿' },
  { id: 3, name: '养生保健' },
  { id: 4, name: '经典理论' },
  { id: 5, name: '四季养生' },
  { id: 6, name: '食疗方案' }
]

// 列表数据
const questionList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)//
const selectedIds = ref([])

// 搜索表单
const searchForm = ref({
  categoryId: '',
  difficulty: ''
})

// 编辑表单
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)
const form = ref({
  id: '',
  type: '',
  categoryId: '',
  content: '',
  optionList: ['', ''],
  answer: '',
  difficulty: 1,
  explanation: ''
})

// 表单验证规则
const rules = {
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入问题内容', trigger: 'blur' }
  ],
  optionList: [
    { required: true, message: '请输入选项内容', trigger: 'blur' }
  ],
  answer: [
    { required: true, message: '请选择正确答案', trigger: 'change' }
  ],
  difficulty: [
    { required: true, message: '请选择难度', trigger: 'change' }
  ]
}

// 获取问题列表
const fetchQuestionList = async () => {
  try {
    const response = await request.get('/api/v1/medical/question/page', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        categoryId: searchForm.value.categoryId || undefined,
        difficulty: searchForm.value.difficulty || undefined
      }
    })
    
    if (response.code === '0000') {
      questionList.value = response.data
      total.value = response.data.length
    }
  } catch (error) {
    console.error('获取问题列表失败:', error)
    ElMessage.error('获取问题列表失败')
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchQuestionList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    categoryId: '',
    difficulty: ''
  }
  handleSearch()
}

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchQuestionList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchQuestionList()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 添加问题
const handleAdd = () => {
  isEdit.value = false
  form.value = {
    id: '',
    type: '',
    categoryId: '',
    content: '',
    optionList: ['', ''],
    answer: '',
    difficulty: 1,
    explanation: ''
  }
  dialogVisible.value = true
}

// 编辑问题
const handleEdit = async (row) => {
  try {
    const response = await request.get(`/api/v1/medical/question/query_question/${row.id}`)
    if (response.code === '0000') {
      const data = response.data
      form.value = {
        id: data.id,
        type: data.type,
        categoryId: data.categoryId,
        content: data.content,
        optionList: data.options ? data.options.split(',') : ['', ''],
        answer: data.answer,
        difficulty: data.difficulty || 1,
        explanation: data.explanation
      }
      isEdit.value = true
      dialogVisible.value = true
    }
  } catch (error) {
    console.error('获取问题详情失败:', error)
    ElMessage.error('获取问题详情失败')
  }
}

// 删除问题
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个问题吗？', '提示', {
      type: 'warning'
    })
    
    const response = await request.delete(`/api/v1/medical/question/delete/${row.id}`)
    if (response.code === '0000') {
      ElMessage.success('删除成功')
      fetchQuestionList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除问题失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的问题')
    return
  }
  
  try {
    await ElMessageBox.confirm('确定要删除选中的问题吗？', '提示', {
      type: 'warning'
    })
    
    const response = await request.post('/api/v1/medical/question/batch/delete', selectedIds.value)
    if (response.code === '0000') {
      ElMessage.success('批量删除成功')
      fetchQuestionList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 保存问题
const handleSave = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    const data = {
      id: form.value.id,
      type: form.value.type,
      categoryId: form.value.categoryId,
      content: form.value.content,
      options: form.value.optionList.join(','),
      answer: form.value.answer,
      difficulty: form.value.difficulty,
      explanation: form.value.explanation
    }
    
    let response
    if (isEdit.value) {
      // 使用PUT方法更新
      response = await request.put('/api/v1/medical/question/update', data)
    } else {
      // 使用POST方法添加
      response = await request.post('/api/v1/medical/question/add', data)
    }
    
    if (response.code === '0000') {
      ElMessage.success(`${isEdit.value ? '更新' : '添加'}成功`)
      dialogVisible.value = false
      fetchQuestionList()
    }
  } catch (error) {
    console.error(`${isEdit.value ? '更新' : '添加'}问题失败:`, error)
    ElMessage.error(`${isEdit.value ? '更新' : '添加'}失败`)
  }
}

// 添加选项
const addOption = () => {
  if (form.value.optionList.length < 6) {
    form.value.optionList.push('')
  }
}

// 删除选项
const removeOption = (index) => {
  form.value.optionList.splice(index, 1)
  // 如果删除的是当前选中的答案，清空答案
  if (form.value.answer === String.fromCharCode(65 + index)) {
    form.value.answer = ''
  }
}

// 获取分类名称
const getCategoryName = (categoryId) => {
  const category = categories.find(c => c.id === categoryId)
  return category ? category.name : '未知分类'
}

// 获取难度标签
const getDifficultyLabel = (difficulty) => {
  switch (difficulty) {
    case 1:
      return '简单'
    case 2:
      return '中等'
    case 3:
      return '困难'
    default:
      return '未知'
  }
}

// 获取难度标签类型
const getDifficultyType = (difficulty) => {
  switch (difficulty) {
    case 1:
      return 'success'
    case 2:
      return 'warning'
    case 3:
      return 'danger'
    default:
      return 'info'
  }
}

onMounted(() => {
  fetchQuestionList()
})
</script>

<style lang="scss" scoped>
.question-manage {
  padding: 20px;
  
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 24px;
      color: #303133;
    }
  }
  
  .search-form {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
  }
  
  .option-item {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;
    
    .el-input {
      flex: 1;
    }
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 